﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pavilion.DesignerTool
{
    public abstract class TrackedNodeBase
    {
        protected ResourceItem ParentResource { get; private set; }
        protected NodeScript ParentNodeScript { get; private set; }

        private NodeBase nodeBase;
        private string originalName;
        private List<GameData> originalGameDataCollection;
        private Dictionary<GameData, TrackedGameData> trackedGameDataCollection;
        private IEnumerable<TrackedGameData> activeGameDataList;

        public TrackedNodeBase(NodeBase nodeBase, NodeScript parentNodescript, ResourceItem parentResource)
        {
            this.nodeBase = nodeBase;
            this.ParentNodeScript = parentNodescript;
            this.ParentResource = parentResource;

            originalName = nodeBase.Name;

            originalGameDataCollection = new List<GameData>(nodeBase.GameDataCollection);
            trackedGameDataCollection = new Dictionary<GameData, TrackedGameData>();

            foreach (GameData gameData in nodeBase.GameDataCollection)
                trackedGameDataCollection.Add(gameData, new TrackedGameData(parentResource, parentNodescript, nodeBase, gameData));
        }

        public virtual void TransferDataReorder()
        {
            if (originalName != nodeBase.Name)
                NodeTransfer.Rename(ParentResource.Name, ParentNodeScript.Name, nodeBase.ParentContainer, originalName, nodeBase.Name);

            CollectionDelta<GameData> collectionDelta = new CollectionDelta<GameData>(originalGameDataCollection, nodeBase.GameDataCollection);
            activeGameDataList = collectionDelta.IdenticalItems.Select((gameData) => trackedGameDataCollection[gameData]);

            foreach (GameData newItem in collectionDelta.NewItems)
                GameDataTransfer.AddGameData(ParentResource.Name, ParentNodeScript.Name, nodeBase, newItem);

            List<GameData> copyOfOriginal = new List<GameData>(originalGameDataCollection);
            foreach (GameData deletedItem in collectionDelta.DeletedItems)
            {
                GameDataTransfer.RemoveGameData(ParentResource.Name, ParentNodeScript.Name, nodeBase, copyOfOriginal.IndexOf(deletedItem));
                copyOfOriginal.Remove(deletedItem);
            }
        }

        public virtual void TransferDataUpdate()
        {
            foreach (TrackedGameData trackedGameData in activeGameDataList)
                trackedGameData.TransferData();
        }
    }
}
